package com.zzh.dialog.xpop.fragment;

import android.graphics.Color;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.zzh.dialog.R;
import com.zzh.dialog.xpop.custom.CustomImageViewerPopup;
import com.zzh.lib.core.utils.HResUtils;
import com.zzh.lib.views.adapter.holder.HSuperViewHolder;
import com.zzh.lib.xpopup.XPopup;
import com.zzh.lib.xpopup.core.BasePopupView;
import com.zzh.lib.xpopup.core.ImageViewerPopupView;
import com.zzh.lib.xpopup.ea.EasyAdapter;
import com.zzh.lib.xpopup.interfaces.OnImageViewerLongPressListener;
import com.zzh.lib.xpopup.interfaces.OnSrcViewUpdateListener;
import com.zzh.lib.xpopup.util.SmartGlideImageLoader;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
import androidx.viewpager2.widget.ViewPager2;

import static com.zzh.dialog.xpop.Constants.list;

/**
 * Description:
 * Create by lxj, at 2019/1/22
 */
public class ImageViewerDemo extends BaseFragment {

    String url1 = "https://t7.baidu.com/it/u=1595072465,3644073269&fm=193&f=GIF";
    String url2 = "https://t7.baidu.com/it/u=1956604245,3662848045&fm=193&f=GIF";

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_image_preview;
    }

    static {
        list.clear();
        list.add("https://t7.baidu.com/it/u=2529476510,3041785782&fm=193&f=GIF");
        list.add("https://t7.baidu.com/it/u=727460147,2222092211&fm=193&f=GIF");
        list.add("https://t7.baidu.com/it/u=2511982910,2454873241&fm=193&f=GIF");
        list.add("https://t7.baidu.com/it/u=825057118,3516313570&fm=193&f=GIF");
        list.add("https://t7.baidu.com/it/u=3435942975,1552946865&fm=193&f=GIF");
        list.add("https://t7.baidu.com/it/u=3569419905,626536365&fm=193&f=GIF");
        list.add("https://t7.baidu.com/it/u=762481686,2214126081&fm=193&f=GIF");
        list.add("https://t7.baidu.com/it/u=3779234486,1094031034&fm=193&f=GIF");
        list.add("https://t7.baidu.com/it/u=4162611394,4275913936&fm=193&f=GIF");
        list.add("https://t7.baidu.com/it/u=1951548898,3927145&fm=193&f=GIF");
        list.add("https://t7.baidu.com/it/u=1831997705,836992814&fm=193&f=GIF");
        list.add("https://t7.baidu.com/it/u=2405382010,1555992666&fm=193&f=GIF");
        list.add("https://t7.baidu.com/it/u=2582370511,530426427&fm=193&f=GIF");
        list.add("https://t7.baidu.com/it/u=2851687453,2321283050&fm=193&f=GIF");
        list.add("https://t7.baidu.com/it/u=3601447414,1764260638&fm=193&f=GIF");
        list.add("https://t7.baidu.com/it/u=4069854689,43753836&fm=193&f=GIF");
        list.add("https://t7.baidu.com/it/u=2141219545,3103086273&fm=193&f=GIF");
        list.add("https://t7.baidu.com/it/u=993577982,1027868784&fm=193&f=GIF");
        list.add("https://t7.baidu.com/it/u=3332251293,4211134448&fm=193&f=GIF");
    }

    RecyclerView recyclerView;
    ImageView image1, image2;
    ViewPager pager;
    ViewPager2 pager2;
    Button btn_custom;

    @Override
    public void init(final View view) {
        view.findViewById(R.id.btnClear).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Glide.get(requireContext()).clearMemory();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Glide.get(requireContext()).clearDiskCache();
                    }
                }).start();
            }
        });
        image1 = view.findViewById(R.id.image1);
        image2 = view.findViewById(R.id.image2);
        pager = view.findViewById(R.id.pager);
        pager2 = view.findViewById(R.id.pager2);
        btn_custom = view.findViewById(R.id.btn_custom);
        recyclerView = view.findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 3));
        recyclerView.setAdapter(new ImageAdapter());


        Glide.with(this).load(url1).into(image1);
        Glide.with(this).load(url2).into(image2);
        image1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new XPopup.Builder(getContext())
                        .isDestroyOnDismiss(true)
                        .asImageViewer(image1, url1, true, Color.parseColor("#f1f1f1"), -1, 0
                                , false, Color.BLACK, new SmartGlideImageLoader(R.mipmap.ic_launcher), new OnImageViewerLongPressListener() {
                                    @Override
                                    public void onLongPressed(BasePopupView popupView, int position) {
                                        Toast.makeText(requireContext(), "长按了第" + position + "个图片", Toast.LENGTH_SHORT).show();
                                    }
                                })
                        .show();
            }
        });
        image2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new XPopup.Builder(getContext())
                        .asImageViewer(image2, url2, new SmartGlideImageLoader())
                        .show();
            }
        });

        //ViewPager bind data
        pager.setOffscreenPageLimit(list.size());
        pager.setAdapter(new ImagePagerAdapter());

        btn_custom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //自定义的弹窗需要用asCustom来显示，之前的asImageViewer这些方法当然不能用了。
                CustomImageViewerPopup viewerPopup = new CustomImageViewerPopup(getContext());
                //自定义的ImageViewer弹窗需要自己手动设置相应的属性，必须设置的有srcView，url和imageLoader。
                viewerPopup.setSingleSrcView(image2, url2);
//                viewerPopup.isInfinite(true);
                viewerPopup.setXPopupImageLoader(new SmartGlideImageLoader());
//                viewerPopup.isShowIndicator(false);//是否显示页码指示器
//                viewerPopup.isShowPlaceholder(false);//是否显示白色占位块
//                viewerPopup.isShowSaveButton(false);//是否显示保存按钮
                new XPopup.Builder(getContext())
                        .isDestroyOnDismiss(true)
                        .asCustom(viewerPopup)
                        .show();
            }
        });

        pager2.setAdapter(new ViewPager2Adapter());
    }

    public static class ImageAdapter extends EasyAdapter<Object> {
        public ImageAdapter() {
            super(list, R.layout.adapter_image);
        }

        @Override
        protected void bind(@NonNull final HSuperViewHolder holder, @NonNull final Object s, final int position) {
            final ImageView imageView = holder.<ImageView>getView(R.id.image);
            //1. 加载图片
            Glide.with(imageView).load(s).apply(new RequestOptions()
                            .transform(new CenterCrop(), new RoundedCorners(HResUtils.dp2px(10))))
                    .error(R.mipmap.ic_launcher).into(imageView);

            //2. 设置点击
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    new XPopup.Builder(holder.itemView.getContext())
//                            .animationDuration(1000)
                            .isTouchThrough(true)
                            .asImageViewer(imageView, position, list,
                                    false, true, -1, -1, HResUtils.dp2px(10), true,
                                    Color.rgb(32, 36, 46),
                                    new OnSrcViewUpdateListener() {
                                        @Override
                                        public void onSrcViewUpdate(ImageViewerPopupView popupView, int position) {
                                            RecyclerView rv = (RecyclerView) holder.itemView.getParent();
                                            popupView.updateSrcView((ImageView) rv.getChildAt(position));
                                        }
                                    }, new SmartGlideImageLoader(true, R.mipmap.ic_launcher), null)
                            .show();
                }
            });
        }
    }

    //ViewPager2的adapter
    public class ViewPager2Adapter extends EasyAdapter<Object> {
        public ViewPager2Adapter() {
            super(list, R.layout.adapter_image2);
        }

        @Override
        public void bind(final HSuperViewHolder holder, final Object s, final int position) {
            final ImageView imageView = holder.getView(R.id.image);
            //1. 加载图片
            Glide.with(imageView).load(s).error(R.mipmap.ic_launcher).into(imageView);

            //2. 设置点击
            imageView.setOnClickListener(v -> new XPopup.Builder(holder.itemView.getContext()).asImageViewer(imageView, position, list,
                            (popupView, position1) -> {
                                pager2.setCurrentItem(position1, false);
                                //一定要post，因为setCurrentItem内部实现是RecyclerView.scrollTo()，这个是异步的
                                pager2.post(() -> {
                                    //由于ViewPager2内部是包裹了一个RecyclerView，而RecyclerView始终维护一个子View
                                    RecyclerView rv = (RecyclerView) pager2.getChildAt(0);
                                    //再拿子View，就是ImageView
                                    popupView.updateSrcView((ImageView) rv.getChildAt(0));
                                });
                            }, new SmartGlideImageLoader())
                    .show());
        }
    }

    class ImagePagerAdapter extends PagerAdapter {
        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public boolean isViewFromObject(@NonNull View view, @NonNull Object o) {
            return view == o;
        }

        @NonNull
        @Override
        public Object instantiateItem(@NonNull ViewGroup container, final int position) {
            final ImageView imageView = new ImageView(container.getContext());
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            container.addView(imageView);

            //1. 加载图片
            Glide.with(imageView).load(list.get(position)).into(imageView);

            //2. 设置点击
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    new XPopup.Builder(getContext())
                            .asImageViewer(imageView, position, list, true, false, -1, -1, -1, true, Color.BLACK, new OnSrcViewUpdateListener() {
                                @Override
                                public void onSrcViewUpdate(final ImageViewerPopupView popupView, final int position) {
                                    //1.pager更新当前显示的图片
                                    //当启用isInfinite时，position会无限增大，需要映射为当前ViewPager中的页
                                    int realPosi = position % list.size();
//                            Log.e("tag", "position: "+realPosi + " list size: "+list.size());
                                    pager.setCurrentItem(position, false);
                                    //2.更新弹窗的srcView，注意这里的position是list中的position，上面ViewPager设置了pageLimit数量，
                                    //保证能拿到child，如果不设置pageLimit，ViewPager默认最多维护3个page，会导致拿不到child
                                    popupView.updateSrcView((ImageView) pager.getChildAt(position));
                                }
                            }, new SmartGlideImageLoader(), null)
                            .show();
                }
            });

            return imageView;
        }

        @Override
        public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
            container.removeView((View) object);
        }
    }

}

